package com.bjbn.aesbcommonapi.config;

import lombok.RequiredArgsConstructor;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

@Configuration
@RequiredArgsConstructor
public class KafkaProducerConfig {
    private final KafkaConfig kafkaConfig;

    @Bean
    public ProducerFactory<String, String> producerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfig.getBootstrapServers());
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, kafkaConfig.getMaxRequestSize());

        // === 大消息核心配置（新增）===

        // 1. 内存缓冲区：512MB（原32MB）
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, kafkaConfig.getProducer().getBufferMemory());

        // 2. 禁用batching（大消息不适合batch，立即发送）
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, kafkaConfig.getProducer().getBatchSize());
        props.put(ProducerConfig.LINGER_MS_CONFIG, kafkaConfig.getProducer().getLingerMs());

        // 3. 启用压缩（必选项，10MB→2-3MB）
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, kafkaConfig.getProducer().getCompressionType());

        // 4. 超时配置（5分钟）
        props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, kafkaConfig.getProducer().getMaxBlockMs());
        props.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, kafkaConfig.getProducer().getRequestTimeoutMs());
        props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, kafkaConfig.getProducer().getDeliveryTimeoutMs());

        // 5. 重试策略（大消息重试成本极高，最多1次）
        props.put(ProducerConfig.RETRIES_CONFIG, kafkaConfig.getProducer().getRetries());
        props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, kafkaConfig.getProducer().getRetryBackoffMs());

        // 6. Socket缓冲区（1MB）
        props.put(ProducerConfig.SEND_BUFFER_CONFIG, kafkaConfig.getProducer().getSendBufferBytes());
        props.put(ProducerConfig.RECEIVE_BUFFER_CONFIG, kafkaConfig.getProducer().getReceiveBufferBytes());

        // 7. ACK机制（权衡可靠性）
        // all: 最高可靠性，但最慢
        // 1: Leader确认，平衡选择
        // 0: 不确认，最快但可能丢失
        props.put(ProducerConfig.ACKS_CONFIG, kafkaConfig.getProducer().getAcks());

        // 8. 其他重要配置
        // 限制单个Producer实例的内存占用
        props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, kafkaConfig.getProducer().getMaxInFlightRequestsPerConnection());

        return new DefaultKafkaProducerFactory<>(props);
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}